package com.iweipan.fragment;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.gson.Gson;
import com.iweipan.R;
import com.iweipan.base.WPBaseFragment;
import com.iweipan.base.WPUrlBase;
import com.iweipan.bean.MinuLineBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/11/18.
 */

public class MinutesLineFragment extends WPBaseFragment {
    @BindView(R.id.chart)
    LineChart chart;
    private int type = 1;


    String[] sss = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
    private List<String> dateList;

    @Override
    public void initData() {
        initChart();

        try {
            JSONObject typeJson = new JSONObject();
            typeJson.put("type", type);
            typeJson.put("contract", "XAG1");

            OkHttpUtils.get()
                    .url(WPUrlBase.Get_Now_KLine)
                    .addParams("p", typeJson.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {

                            String code = null;
                            try {
//                                Log.e("MinutesLineFragment", response);
                                JSONObject jsonObject = new JSONObject(response);
                                code = jsonObject.getString("code");
                                if (code.equals("200")) {
                                    Gson gson = new Gson();
                                    MinuLineBean minuLineBean = gson.fromJson(response, MinuLineBean.class);
                                    MinuLineBean.ResultBean result = minuLineBean.getResult();
                                    List<String> dataList = result.getDataList();
                                    dateList = result.getDateList();

                                    if (dataList != null && dataList.size() > 0) {
                                        ArrayList<Entry> yVals = new ArrayList<Entry>();

                                        for (int i = 0; i < dataList.size(); i++) {
                                            Entry entry = new Entry(i, Float.parseFloat(dataList.get(dataList.size() - i - 1)));
                                            yVals.add(entry);
                                        }
                                        setData(yVals);
                                        chart.animateXY(2000, 200);
                                        // dont forget to refresh the drawing
                                        chart.invalidate();

                                    }

                                } else if (code.equals("1100")) {

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void initDestrory() {

    }

    @Override
    public void initView() {
    }

    private void initChart() {
        chart.setBackgroundColor(Color.rgb(250, 250, 250));
        chart.setDrawBorders(true);
        chart.setScaleEnabled(false);

        chart.setBorderWidth(1);
        chart.setBorderColor(getResources().getColor(R.color.colorAccent));
        chart.getDescription().setEnabled(false);

        Legend lineChartLegend = chart.getLegend();
        lineChartLegend.setEnabled(false);

        MyMarkerView myMarkerView = new MyMarkerView(mActivity, R.layout.klin_text);
        myMarkerView.setChartView(chart);
        chart.setMarker(myMarkerView);
        XAxis xAxis = chart.getXAxis();

//        xAxis.setAxisMaximum(1000);
//        xAxis.setLabelCount(3, true);

        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                return dateList.get(dateList.size() - (int) value-1);
            }

        });
        xAxis.setDrawGridLines(true);
        xAxis.setDrawLabels(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        YAxis axisLeft = chart.getAxisLeft();
        axisLeft.setLabelCount(5, true);
        axisLeft.setTextColor(Color.BLACK);
//        axisLeft.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        axisLeft.setDrawGridLines(false);
        axisLeft.setDrawLabels(true);
        axisLeft.setAxisLineColor(Color.BLACK);
        axisLeft.setDrawAxisLine(false);


        YAxis axisRight = chart.getAxisRight();
        axisRight.setEnabled(false);
    }

    @Override
    public View inflaterView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_minutes, null);
    }

    private class MyMarkerView extends MarkerView {
        private TextView textView;

        /**
         * Constructor. Sets up the MarkerView with a custom layout resource.
         *
         * @param context
         * @param layoutResource the layout resource to use for the MarkerView
         */
        public MyMarkerView(Context context, int layoutResource) {
            super(context, layoutResource);
            textView = (TextView) findViewById(R.id.tvContent);
        }

        @Override
        public void refreshContent(Entry e, Highlight highlight) {
            if (e instanceof CandleEntry) {
                CandleEntry candleEntry = (CandleEntry) e;
                textView.setText("" + (int) candleEntry.getHigh());
            } else {
                textView.setText("" + (int) e.getY());
            }
            super.refreshContent(e, highlight);
        }

        @Override
        public MPPointF getOffset() {
            return new MPPointF(-(getWidth() / 2), -getHeight());
        }
    }


    private void setData(ArrayList<Entry> yVals) {

        LineDataSet lineDataSet;

        if (chart.getData() != null &&
                chart.getData().getDataSetCount() > 0) {
            lineDataSet = (LineDataSet) chart.getData().getDataSetByIndex(0);
            lineDataSet.setValues(yVals);
            chart.getData().notifyDataChanged();
            chart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            lineDataSet = new LineDataSet(yVals, "");

            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            lineDataSet.setCubicIntensity(0.2f);
            lineDataSet.setDrawFilled(true); // 设置填充
            lineDataSet.setDrawCircles(false);
            lineDataSet.setLineWidth(1.8f);
            lineDataSet.setCircleRadius(4f);
            lineDataSet.setCircleColor(Color.rgb(0, 133, 244));
            lineDataSet.setHighLightColor(Color.rgb(244, 117, 117));
            lineDataSet.setColor(Color.rgb(0, 133, 244));
            lineDataSet.setFillColor(Color.rgb(0, 133, 244));
            lineDataSet.setFillAlpha(100);
            lineDataSet.setDrawHorizontalHighlightIndicator(true);

            // create a data object with the datasets
            LineData data = new LineData(lineDataSet);

            data.setValueTextSize(9f);
            data.setDrawValues(false);

            // set data
            chart.setData(data);
        }
    }

}
